package com.dongdxiang.framework;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.dongdxiang.framework.dialog.ImageDialog;
import com.dongdxiang.framework.dialog.Snackbar;
import com.dongdxiang.framework.dialog.WebDialog;
import com.dongdxiang.framework.http.CallServer;
import com.dongdxiang.framework.http.FastJsonRequest;
import com.dongdxiang.framework.http.HttpListener;
import com.dongdxiang.framework.http.QjResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;
import com.yolanda.nohttp.rest.StringRequest;
import com.yolanda.nohttp.tools.HeaderParser;
import org.json.JSONObject;

/**
 * Created by d_xxiang on 2016/10/13.
 */
public abstract class BaseActivity extends AppCompatActivity {

    public static BaseActivity baseActivity ;
//    private CoordinatorLayout mCoordinatorLayout;
    private AppBarLayout mAppBarLayout;
    private Toolbar mToolbar;
    private FrameLayout mContentLayout;
    private TextView title;
    private TextView btn_right;
    private TextView btn_left;
    private LinearLayout view_center;
    //防止重复点击设置的标志，涉及到点击打开其他Activity时，将该标志设置为false，在onResume事件中设置为true
    private boolean clickable=true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getDelegate().setContentView(R.layout.activity_base);
//        mCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorlayout);
        mAppBarLayout = (AppBarLayout) findViewById(R.id.appbarlayout);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mContentLayout = (FrameLayout) findViewById(R.id.content);
        title = (TextView) findViewById(R.id.title);
        btn_right = (TextView) findViewById(R.id.btn_right);
        btn_left = (TextView) findViewById(R.id.btn_left);
        view_center = (LinearLayout)findViewById(R.id.view_center);
        setSupportActionBar(mToolbar);
        setBackBar(false);
        onActivityCreate(savedInstanceState);
        baseActivity = this;
    }

    public void setCenterTitle(CharSequence str){
        title.setText(str);
    }

    public void setCenterTitle(int stringId){
        title.setText(stringId);
    }

//    public void setLeft_Btn(int drawableId , View.OnClickListener onClickListener){
//        Drawable drawable = getResources().getDrawable(drawableId);
//        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
//        btn_left.setCompoundDrawables(drawable, null, null, null);//画在左边
//        btn_left.setOnClickListener(onClickListener);
//    }

    public void setLeft_Btn(int stringId , View.OnClickListener onClickListener) {
        btn_left.setText(stringId);
        btn_left.setOnClickListener(onClickListener);
    }

    public void setLeft_Btn(String stringId , int drawableId , View.OnClickListener onClickListener) {
        btn_left.setText(stringId);
        btn_left.setOnClickListener(onClickListener);
        if (drawableId == 0) return;
        Drawable drawable = getResources().getDrawable(drawableId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
        btn_left.setCompoundDrawables(drawable, null, null, null);//画在左边
    }

    public void setLeft_Btn(CharSequence str , int drawableId){
        btn_left.setText(str);
        if (drawableId == 0) return;
        Drawable drawable = getResources().getDrawable(drawableId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
        btn_left.setCompoundDrawables(drawable, null, null, null);//画在左边
    }
    public void setLeft_Btn(CharSequence str){
        btn_left.setText(str);
    }


    public void setLeft_Btn(int strId , int drawableId){
        btn_left.setText(strId);
        if (drawableId == 0) return;
        Drawable drawable = getResources().getDrawable(drawableId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
        btn_left.setCompoundDrawables(drawable, null, null, null);//画在左边
    }

//    public void setRight_Btn(int drawableId, View.OnClickListener onClickListener){
//        Drawable drawable = getResources().getDrawable(drawableId);
//        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
//        btn_right.setCompoundDrawables(drawable, null, null, null);//画在左边
//        btn_right.setOnClickListener(onClickListener);
//    }

    public void setRight_Btn(int stringId, View.OnClickListener onClickListener){
        btn_right.setText(stringId);
        btn_right.setOnClickListener(onClickListener);
    }

    public void setRight_Btn(CharSequence str , int drawableId){
        btn_right.setText(str);
        if (drawableId == 0) return;
        Drawable drawable = getResources().getDrawable(drawableId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
        btn_right.setCompoundDrawables(null, null, drawable, null);//画在左边
    }

    public void setRight_Btn(int strId , int drawableId){
        btn_right.setText(strId);
        Drawable drawable = getResources().getDrawable(drawableId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
        btn_right.setCompoundDrawables(null, null, drawable, null);//画在左边
    }

    public void initHeardView(View view){
        if (view_center.getChildCount() > 0){
            view_center.removeAllViews();
        }
        view_center.addView(view);
    }


    public <T extends View> T findView(int viewId) {
        return (T) mContentLayout.findViewById(viewId);
    }

    @Override
    public void setContentView(int layoutResID) {
        mContentLayout.removeAllViews();
        getLayoutInflater().inflate(layoutResID, mContentLayout, true);
    }

    @Override
    public void setContentView(View view) {
        mContentLayout.removeAllViews();
        mContentLayout.addView(view);
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        mContentLayout.addView(view, params);
    }

    public void setBackBar(boolean isShow) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(isShow);
    }

    protected abstract void onActivityCreate(Bundle savedInstanceState);


    public ViewGroup getContentRoot() {
        return mContentLayout;
    }
    /**
     * Show message dialog.
     *
     * @param title   title.
     * @param message message.
     */
    public void showMessageDialog(int title, int message) {
        showMessageDialog(getText(title), getText(message));
    }

    /**
     * Show message dialog.
     *
     * @param title   title.
     * @param message message.
     */
    public void showMessageDialog(int title, CharSequence message) {
        showMessageDialog(getText(title), message);
    }

    /**
     * Show message dialog.
     *
     * @param title   title.
     * @param message message.
     */
    public void showMessageDialog(CharSequence title, int message) {
        showMessageDialog(title, getText(message));
    }

    /**
     * Show message dialog.
     *
     * @param title   title.
     * @param message message.
     */
    public void showMessageDialog(CharSequence title, CharSequence message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton("kow", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    /**
     * Show message dialog.
     *
     * @param title   title.
     * @param message message.
     */
    public void showExitDialog(CharSequence title, CharSequence message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton("kow", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                System.exit(0);
            }
        });
        builder.show();
    }

    /**
     * 显示图片dialog。
     *
     * @param title  标题。
     * @param bitmap 图片。
     */
    public void showImageDialog(CharSequence title, Bitmap bitmap) {
        ImageDialog imageDialog = new ImageDialog(this);
        imageDialog.setTitle(title);
        imageDialog.setImage(bitmap);
        imageDialog.show();
    }

    /**
     * 显示一个WebDialog。
     *
     * @param response 响应。
     */
    public void showWebDialog(Response<?> response) {
        String result = StringRequest.parseResponseString(response.getHeaders(), response.getByteArray());
        WebDialog webDialog = new WebDialog(this);
        String contentType = response.getHeaders().getContentType();
        webDialog.loadUrl(result, contentType, HeaderParser.parseHeadValue(contentType, "charset", "utf-8"));
        webDialog.show();
    }


    /**====================================================Http request======================================*/
    public <T> void httpGetRequest(int what, String url, TypeToken typeToken, boolean canCancel, boolean isLoading) {
        RequestMethod requestMethod = RequestMethod.GET;
        request(what, url, typeToken, canCancel, isLoading, requestMethod);
    }
    public <T> void httpPostRequest(int what, String url, TypeToken typeToken, boolean canCancel, boolean isLoading ,JSONObject jsonParams) {
        RequestMethod requestMethod = RequestMethod.POST;
        request(what, url, typeToken, canCancel, isLoading,jsonParams,requestMethod);
    }
    public <T> void httpPutRequest(int what, String url,TypeToken typeToken, boolean canCancel, boolean isLoading) {
        RequestMethod requestMethod = RequestMethod.PUT;
        request(what, url, typeToken, canCancel, isLoading,requestMethod);
    }
    public <T> void httpDeleteRequest(int what, String url, TypeToken typeToken,boolean canCancel, boolean isLoading) {
        RequestMethod requestMethod = RequestMethod.DELETE;
        request(what, url, typeToken, canCancel, isLoading,requestMethod);
    }

    public <T> void request(int what, String url,TypeToken typeToken, boolean canCancel, boolean isLoading,RequestMethod requestMethod) {
        Request<JSONObject> request = new FastJsonRequest(url, requestMethod);
        request.setCancelSign(this);
        CallServer.getRequestInstance().add(this, what, request, httpListener,typeToken, canCancel, isLoading);
    }

    public <T> void request(int what, String url,TypeToken typeToken, boolean canCancel, boolean isLoading ,JSONObject jsonObject,RequestMethod requestMethod) {
        Request<JSONObject> request = new FastJsonRequest(url, requestMethod);
        request.setCancelSign(this);
        request.setDefineRequestBodyForJson(jsonObject);
        CallServer.getRequestInstance().add(this, what, request, httpListener,typeToken, canCancel, isLoading);
    }

    private HttpListener<JSONObject> httpListener = new HttpListener<JSONObject>() {
        @Override
        public void onSucceed(int what, Response<JSONObject> response , TypeToken typeToken , Object object) {
            if (response != null && response.get() != null){
                Gson gson = new Gson();
                java.lang.reflect.Type type = typeToken.getType();
                String str = response.get().toString();

                QjResult result = gson.fromJson(str, type);
                if (result != null && result.getResult() != null)
                    if ("200".equals(result.getStatus_code())){
                        baseActivity.onSucceed( what,result.getResult());
                    }else {
                        Snackbar.show(baseActivity, result.message());
                    }
                else {
                    Snackbar.show(baseActivity, "请求失败！");
                }
            }
        }

        @Override
        public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {
            baseActivity.onFailed( what,  url,  tag,  exception,  responseCode,  networkMillis);
        }
    };

    protected abstract void onSucceed(int what, Object response);
    protected abstract void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis);


    @Override
    protected void onDestroy() {
        super.onDestroy();
        CallServer.getRequestInstance().cancelBySign(this);
        Log.e("===",this.getClass().getSimpleName()+"==> onDestroy");
    }


    @Override
    protected void onResume() {
        super.onResume();
        //每次返回界面时，将点击标志设置为可点击
        clickable=true;
    }

    /**
     * 当前是否可以点击
     * @return
     */
    protected boolean isClickable(){
        return  clickable;
    }

    /**
     * 锁定点击
     */
    protected void lockClick(){
        clickable=false;
    }
    @Override
    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
        if(isClickable()) {
            lockClick();
            super.startActivityForResult(intent, requestCode,options);
        }
    }
}

